/**
 * @brief  bsp_key.c/h
 * @param  按键状态机的设定以及CAN_ID的设置
 * @author 颜福兵
 * @date   2022/9/5
 * 
 **/
#ifdef __cplusplus
extern "C"
{
#endif
  
#include "bsp_key.h"
#include "bsp_micros.h"
#include "bsp_delay.h"
#include "tim.h"
#include "main.h"
#include "oled_display.h"
uint16_t button_time = 0;
uint8_t key_flag=BUTTON_TIMES;
uint32_t key_sleep_time;
uint16_t button_Value[3];



extern int8_t key0;
extern int8_t key1;

extern volatile uint8_t now_menu_index;  //当前的菜单栏目录
 uint32_t id_reading;
/**
 * @brief 按键扫描(放在函数里面执行)
 * @param  
 */
 void  key_Scanf(void) {
	 if (!HAL_GPIO_ReadPin(KEY0_GPIO_Port, KEY0_Pin)) {
		 button_time++;
	 }
	 else {
		 button_time = 0;
	 }
	 if (button_time >= 2000) {
		 key_flag = LONG_TIME;
		 HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, 1);
		 key_sleep_time = millis();
	 }
	 if (key_flag == LONG_TIME) {
		 if (millis() - key_sleep_time >= 2000) {
			 if (button_Value[0]) {
				 HAL_GPIO_TogglePin(LED1_GPIO_Port, LED0_Pin);
				 if (millis() - key_sleep_time >= 2500) {
					 Flash_WriteData(PARA_ADDR, button_Value[0] + 0x200);
					 id_reading = Flash_ReadData(PARA_ADDR);
					 button_Value[0] = 0;             //按键值复位清零
					 key_flag = BUTTON_TIMES;         //清除标志位
					 HAL_GPIO_WritePin(LED0_GPIO_Port, LED0_Pin, 0);
					 return;
				 }
				 else {
					 return;
				 }
			 }
			 else {
				 key_flag = BUTTON_TIMES;         //清除标志位
			 }
		 }
		 else {
			 return;
		 }
	 }
 }


/**
 * @brief 外部中断回调函数
 * @param GPIO_Pin 
 */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
	if (GPIO_Pin == KEY0_Pin) {
			if(key0>=40)
		{
			key0+=0;
		}else
		{
		key0+=5;
		}
		if (!HAL_GPIO_ReadPin(KEY0_GPIO_Port, KEY0_Pin)) {
			switch (key_flag) {
			case BUTTON_TIMES:
				now_menu_index = key_index[now_menu_index].enter_index;
				break;
			case LONG_TIME:
				key_sleep_time = millis();
				HAL_GPIO_TogglePin(LED0_GPIO_Port, LED0_Pin);
				delay_ms(100);
				HAL_GPIO_TogglePin(LED0_GPIO_Port, LED0_Pin);
				button_Value[0]++;
				break;
			default:
				break;
			}
		}
	}
	else if(GPIO_Pin==KEY1_Pin)
	{
	now_menu_index = key_index[now_menu_index].down_index;
		if(key0<=-40)
		{
	   key0-=0;
		}else
		{
	   key0-=5;
		}
	}
}

/**
 * @brief 获取按键的值
 * @param i 按键的位号
 * @return 按键的指针
 */
const uint16_t* get_key_value_point(uint8_t i) {
	return &button_Value[i & 0x03];
}


#ifdef __cplusplus
}
#endif


